/*
 * @Description: 档案导出管理上下文
 * @Author: Rfan
 * @Date: 2022-06-21 21:37:30
 * @LastEditTime: 2022-09-25 16:57:31
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { message, Modal } from 'antd';
import {
  SET_EXPORT_LIST,
  DELETE_EXPORT_ITEM,
  SET_SELECTED_ITEM,
  SET_SELECT_EXPORT_TYPE,
  DELETE_EXPORT_ORIGIN,
  SET_EXPORT_ITEM_PROCESS,
  EDIT_EXPORT_LIST
} from '../constants';
import { ExportMgtReducer } from '../reducers/ExportMgtReducer';
import {
  deleteExportItem,
  deleteExportOrigin,
  fetchExportListByPage,
  startDetection,
  startPackage,
  startTransfer
} from '@/api/archives/export';
import { selectItemByKey } from '@/utils/list';
import { stateList } from '../dictionaries';
import { EnumReceiveTypes, receiveTypeList } from '@/dictionary/transfer';

const initialState = {
  // 当前选中的项目
  selectExportType: EnumReceiveTypes.Excel,
  fondsList: [],
  ATList: [],
  levelList: [],
  // 导出列表
  exportList: [],
  // 选中的表格条目
  selectItems: [],

  // -------- 字典 --------
  // 接收类型列表
  exportTypeList: receiveTypeList,

  // 批次状态列表
  stateList
};

const ExportMgtContext = createContext();

const ExportMgtContextProvider = (props) => {
  const [state, dispatch] = useReducer(ExportMgtReducer, initialState);

  const actions = {
    /**
     * @description: 设置选中的导出类型
     */
    setSelectExportType(data) {
      dispatch({ type: SET_SELECT_EXPORT_TYPE, data });
    },

    /**
     * @description: 设置表格中选中条目的key
     * @param {*} selectArr
     * @return {*}
     */
    setSelectKey(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },

    /**
     * @description: 获取导出列表方法
     * @param {IExportListParams} params 参数
     * @return {Promise}
     */
    getExportListFunc(params) {
      return new Promise((resolve, reject) => {
        fetchExportListByPage(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_EXPORT_LIST, data: data.results });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 删除导出条目
     * @param {number|number[]} id
     * @param {string} title
     */
    deleteExportOriginFunc(id, title = '确认删除此条导出单原文？') {
      Modal.confirm({
        title: '删除',
        content: title,
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteExportOrigin(ids).then(() => {
            message.success('删除原文成功');
            dispatch({ type: DELETE_EXPORT_ORIGIN, ids: id });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    },

    /**
     * @description: 删除导出条目
     * @param {number|number[]} id
     * @param {string} title
     */
    deleteExportFunc(id, title = '确认删除此条导出单？') {
      Modal.confirm({
        title: '删除',
        content: title,
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteExportItem(ids).then((res) => {
            message.success('删除成功');
            const data = res.data.map((item) => parseInt(item, 10));
            dispatch({ type: DELETE_EXPORT_ITEM, ids: data });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    },

    /**
     * @description: 设置列表进度
     * @param {*} data websocket进度信息
     * @return {*}
     */
    setExportItemProcess(data) {
      const { businessId } = data;
      const item = selectItemByKey(businessId, state.exportList, 'recordNo');
      if (item) {
        dispatch({ type: SET_EXPORT_ITEM_PROCESS, data, item });
      }
    },

    /**
     * @description: 开始检测任务
     * @param {number} id 条目id
     * @return {*}
     */
    startDetectTaskFunc(id) {
      startDetection(id).then((res) => {
        const { data } = res;
        dispatch({ type: EDIT_EXPORT_LIST, data, id: data.id });
      });
    },

    /**
     * @description: 开始打包任务
     * @param {number} id 条目id
     * @return {*}
     */
    startPackageTaskFunc(id) {
      startPackage(id).then((res) => {
        const { data } = res;
        dispatch({ type: EDIT_EXPORT_LIST, data, id: data.id });
      });
    },

    /**
     * @description: 开始检测任务
     * @param {number} id 条目id
     * @return {*}
     */
    startTransferTaskFunc(id) {
      startTransfer(id).then((res) => {
        const { data } = res;
        dispatch({ type: EDIT_EXPORT_LIST, data, id: data.id });
      });
    }
  };

  const filters = {
    exportTypeFilter(id) {
      return state.exportTypeList.find((item) => item.id === id)?.name || '-';
    },
    stateFilter(id) {
      return state.stateList.find((item) => item.id === id)?.name || '-';
    },
    stateColorFilter(id) {
      return state.stateList.find((item) => item.id === id)?.color || 'blue';
    }
  };

  useEffect(() => {}, []);

  return (
    <ExportMgtContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </ExportMgtContext.Provider>
  );
};

export const useExportMgtContext = () => {
  return useContext(ExportMgtContext);
};

export { ExportMgtContext, ExportMgtContextProvider };
